ISP
在需要多型時,會比較容易為類別實作對應方法。
DIP
以往都是高階去依賴低階,依賴反轉,使得低階依賴高階的需求抽象。
高階模組不應該依賴於低階模組,兩者都應該依賴於抽象介面。
不應該直接去受到實作的影響,而是只要關注在所需要的功能。
依賴:抽象
反轉:(原本)高階依賴低階這件事
小明想喝飲料,透過抽象介面(飲料),飲料當中可能有有分很多飲料(細節),這樣在之後如果有要新增飲料的話就不用去更新原本的程式碼,而是再新增一種新的飲料就好。
from abc import ABCMeta, abstractmethod
from cmath import pi
class Calculate(metaclass=ABCMeta):
@abstractmethod
def get_area(self):
pass
class Square(Calculate):
def __init__(self, h, w):
self.h = h
self.w = w
def get_area(self):
print(self.h * self.w)
class Circle(Calculate):
def __init__(self, r):
self.r = r
def get_area(self):
print(self.r * self.r * pi)
square = Square(3,3)
square.get_area()
circle = Circle(2)
circle.get_area()
class Account:
def __init__(self, pwd):
self.pwd = pwd
@property
def password(self):
return self.pwd
danny = Account("123")
print(danny.password)
danny.password = "4444" #AttributeError: can't set attribute
class Bank_acount:
def __init__(self):
self._password = '0000'
@property
def password(self):
return self._password
@password.setter
def password(self, value):
self._password = value
@password.deleter
def password(self):
del self._password
print('del complite')
andy = Bank_acount()
print(andy.password) #getter
andy.password = '1234' #setter
del andy.password #delete
setter
可以透過在set的時候進行判斷
class Bank_acount:
def __init__(self):
self._password = '0000'
@property
def password(self):
return self._password
@password.setter
def password(self, value):
if len(value) < 6:
print("密碼長度至少要六個")
return
self._password = value
andy = Bank_acount()
print(andy.password) #0000
andy.password = '123456'
print(andy.password) #123456